<template>
  <BasicModal
    v-bind="$attrs"
    :title="props.attributesSelect == 'many' ? '添加动态参数' : '添加静态属性'"
    :help-message="props.attributesSelect == 'many' ? 'add attributes' : 'add parameter'"
    @register="register"
    @ok="handleOk"
  >
    <a-form :model="state.formState" :label-col="{ span: 4 }" :wrapper-col="{ span: 20 }">
      <a-form-item label="参数名称" name="attr_name">
        <a-input v-model:value="state.formState.attr_name" />
      </a-form-item>
      <a-form-item name="attr_vals">
        <div v-for="item in state.formState.attr_vals" :key="item" class="m-3 inline-block">
          <a-tag color="processing" closable @close.prevent="handleDeleteTag(item)">{{
            item
          }}</a-tag>
        </div>
        <div class="m-3 inline-block">
          <a-button v-if="!state.editStatus" size="small" @click="handleAddTag"
            ><PlusOutlined />新增标签</a-button
          >
          <a-input
            v-else
            size="small"
            :maxlength="30"
            style="width: 100px"
            ref="attributeInput"
            v-model:value="state.attributeValue"
            @press-enter.prevent="handleConfirm"
            @blur.prevent="handleConfirm"
          >
            <template #suffix>
              <a class="ml-2 text-red-500 hover:text-red-600" @click="handleCancel">
                <CloseCircleFilled />
              </a>
            </template>
          </a-input>
        </div>
      </a-form-item>
    </a-form>
  </BasicModal>
</template>
<script lang="ts" setup>
  import { message } from 'ant-design-vue';
  import { reactive, watch } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { useShopGoodsStore } from '/@/store/modules/shopGoodsStore';
  import { PlusOutlined, CloseCircleFilled } from '@ant-design/icons-vue';

  type stateModel = {
    formState: { attr_name: string; attr_vals: string[] };
    editStatus: boolean;
    attributeValue: string;
  };

  const [register, { closeModal, setModalProps }] = useModalInner();

  const shopGoodsStore = useShopGoodsStore();

  const props = defineProps({
    id: Number,
    isEdit: Boolean,
    editRow: Object,
    attributesSelect: String,
  });

  const emits = defineEmits(['getAddResult', 'updateAttribute']);

  const state: stateModel = reactive({
    formState: {
      attr_name: '',
      attr_vals: [],
    },
    editStatus: false,
    attributeValue: '',
  });

  const handleOk = () => {
    if (!state.formState.attr_name) return;
    const id: number | any = props.id;
    let attr_vals: string | any;
    if (props.attributesSelect == 'many') {
      attr_vals = state.formState.attr_vals.join(',');
    }
    if (props.attributesSelect == 'only') {
      attr_vals = state.formState.attr_vals.join(' ');
    }
    if (props.isEdit) {
      emits('updateAttribute', [id, props.editRow?.attr_id, state.formState.attr_name, attr_vals]);
    } else {
      addAttribute(id, attr_vals);
    }
    closeModal();
  };

  const addAttribute = async (id: number, attr_vals: string) => {
    const attr_sel: string | any = props.attributesSelect;

    try {
      const row = await shopGoodsStore.addAttributes({
        id,
        attr_name: state.formState.attr_name,
        attr_sel,
        attr_vals,
      });
      message.success('添加成功');
      emits('getAddResult', row);
    } catch (error) {
      console.error(error);
    }
  };

  const handleAddTag = () => {
    state.editStatus = true;
  };

  const handleConfirm = () => {
    state.editStatus = false;
    if (!state.attributeValue) return;
    state.formState.attr_vals.push(state.attributeValue);
    state.attributeValue = '';
  };

  const handleCancel = () => {
    state.editStatus = false;
    state.attributeValue = '';
  };

  const handleDeleteTag = (item: any) => {
    state.formState.attr_vals = state.formState.attr_vals.filter((listItem: any) => {
      return listItem != item;
    });
  };

  const getSingleData = async () => {
    const id: number | any = props.id;
    try {
      const data = await shopGoodsStore.getSingleAttribute({
        id,
        attr_id: props.editRow?.attr_id,
        attr_sel: props.editRow?.attr_sel,
      });
      state.formState.attr_name = data.attr_name;
      state.formState.attr_vals = data.attr_vals;
    } catch (error) {
      console.log(error);
    }
  };

  watch(
    () => props.isEdit,
    (isEdit) => {
      const title = `${props.isEdit ? '修改' : '添加'}${
        props.attributesSelect == 'many' ? '动态参数' : '静态属性'
      }`;
      const helpMessage = [
        `${props.isEdit ? 'edit' : 'add'} ${
          props.attributesSelect == 'many' ? 'attributes' : 'parameter'
        }`,
      ];
      setModalProps({
        title,
        helpMessage,
      });
      if (isEdit) {
        getSingleData();
      }
    },
  );
</script>
